from flask import Blueprint, request, jsonify, abort

from utils.intent.predict import intent_analyze
from store import intents
from utils.parse import request_parse
import re



api = Blueprint('intent',__name__)


@api.route('/api/intent/add',methods=['POST'])
def intent_add():
    data = request_parse(request)
    intent = re.sub(r'[^\w\s]', ' ', data["intent"]).strip().split()
    start_datetime = data["start_datetime"]
    end_datetime = data["end_datetime"]
    src_ip = data["src_ip"]
    service_type, qos_value = intent_analyze(intent)
    #todo 资源验证
    intents.add_intent(intent, start_datetime, end_datetime, src_ip, service_type, qos_value)
    return "OK"

@api.route('/api/background/add', methods=['POST'])
def background_add():
    try:
        data=request_parse(request)
        start_datetime = data["start_datetime"]
        end_datetime = data["end_datetime"]
        src_ip = data["src_ip"]
        dst_ip = data['dst_ip']
        dst_port = data['dst_port']
        slice_type = data['slice_type']
        up_throughput = data['up_throughput']
        down_throughput = data['down_throughput']
        delay = data['delay']
        loss = data['loss']
        intents.add_background_intent(start_datetime,end_datetime,src_ip,dst_ip,dst_port,up_throughput,down_throughput,loss,delay, slice_type)
        return "OK"
    except KeyError:
        abort(400)
    

@api.route('/api/intents',methods=['GET'])
def get_intents():
    return jsonify(intents.get_intents_json())


@api.route('/api/intent/del',methods=['DELETE'])
def del_intent():
    data = request_parse(request)
    try:
        id = data.get("id")
    except:
        abort(400)
    if intents.del_intent(id) == 0:
        return "OK"
    else:
        return "Not sunch intent."
    
@api.route('/api/intent/every_slice_intents', methods = ['GET'])
def get_every_slice_intents():
    return jsonify(intents.get_every_slice_intents())


@api.route('/api/intent/every_service_intents', methods = ['GET'])
def get_every_service_intents():
    return jsonify(intents.get_every_service_intents())